package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.*;
import com.itheima.pojo.AssessmentRisk;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
   @Autowired
   private MemberMapper memberMapper;
   @Autowired
   private AssessmentMapper assessmentMapper;
   @Autowired
   private RiskMapper riskMapper;
   @Autowired
   private PsychologyMapper psychologyMapper;
   @Autowired
   private OrderMapper orderMapper;

   //通过电话查询会员信息
   public Member findByTelephone(String telephone) {
      Member member = memberMapper.findByTelephone(telephone);
      return member;
   }

   //添加会员信息
   public void add(Member member) {
      String password = member.getPassword();
      if (password != null) {
         //进行加密
         member.setPassword(MD5Utils.md5(password));
      }
      memberMapper.add(member);
   }

   //根据月份查询成员已有总数
   public List<Integer> findCountByMonth(List<String> months) {
      List<Integer> memberCount = new ArrayList<>();
      if (months != null && months.size() > 0) {
         //遍历集合
         for (String month : months) {
            //month结构:2020.5
            Integer count = memberMapper.findMemberCountBeforeDate(month + ".31");
            memberCount.add(count);
         }
         return memberCount;
      }
      return null;
   }

   //通过日期查询会员数量
   public Integer findCountByDate(String dateString) {
      Integer count = memberMapper.findCountByCount(dateString);
      return count;
   }

   //查询所有会员数
   public Integer findCountAll() {
      Integer countAll = memberMapper.findCountAll();
      return countAll;
   }

   //查询本周新增会员数
   public Integer findCountByThisWeek(String mondayString, String currentDateString) {
      Integer thisWeekNewMember = memberMapper.findCountOfDateScope(mondayString,currentDateString);
      return thisWeekNewMember;
   }

   //查询本月新增会员数
   public Integer findCountByThisMonth(String firstDayOfThisMonthStr, String currentDateString) {
      return memberMapper.findCountOfDateScope(firstDayOfThisMonthStr, currentDateString);
   }



    //查询会员体检上传页面展示
    public PageResult findPageBySC(QueryPageBean queryPageBean){
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        //mybatis分页助手
        PageHelper.startPage(currentPage,pageSize);
        //根据条件查询
        Page<Map> page = memberMapper.findPageBySC(queryString);
        long total = page.getTotal();
        List<Map> result = page.getResult();
        for (Map map : result) {
            for (Object key : map.keySet()) {
                //根据键获取值
                //处理时间
                if (key.equals("regTime")){
                    Date date = (Date) map.get(key);
                    String stringDate = null;
                    try {
                        stringDate = DateUtils.parseDate2String(date);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    map.put(key,stringDate);
                }
                //处理报告上传状态
                if (key.equals("orderStatus")){
                    Object value = map.get(key);
                    if (value.equals("未到诊")){
                        map.put(key,"报告未上传");
                    }else {
                        map.put(key,"报告已上传");
                    }
                }
            }
        }
        return new PageResult(total,result);
    }

    //根据会员电话删除体检上传信息
    public Map deleteByPhoeNumber(String phoneNumber) {
        //根据电话查询会员
        Member member = memberMapper.findByTelephone(phoneNumber);
        Integer memberId = member.getId();
        //根据会员id删除order表
        memberMapper.deleteOrderByMemberId(memberId);
        //查询该会员的体检报告名称
        Map fileNameMap = memberMapper.findFileName(memberId);
        //根据会员id删除体检报告表
        memberMapper.deleteDoc(memberId);

        //删除会员的健康测评记录
        assessmentMapper.deleteMember(memberId);
        psychologyMapper.deleteMember(memberId);
        riskMapper.deleteMember(memberId);

        //根据会员id删除会员
        memberMapper.deleteById(memberId);
        return fileNameMap;
    }

    //将上传的文件名对应会员保存到数据库
    public void setFileName(String phoneNumber,String fileName) {
        //文件上传完毕，修改会员报告状态
        //根据会员电话查询会员
        Member member = memberMapper.findByTelephone(phoneNumber);
        Integer memberId = member.getId();
        //根据会员id修改order表中的是否到诊状态
        memberMapper.updateTypeById(memberId);

        //添加文件名
        Map<String,Object> map = new HashMap<>();
        map.put("memberId",memberId);
        map.put("fileName",fileName);
        memberMapper.setFileName(map);

        //将会员添加到健康评估表--体质
        assessmentMapper.addMember(memberId);
        //将会员添加到健康评估表--心理
        psychologyMapper.addMember(memberId);
        //将会员添加到健康评估表--风险
        riskMapper.addMember(memberId);
    }



    //获取用户统计数据,包括:当前日期,本月会员预约数,会员总数
    public Map<String, Object> getMemberStatistics(Map<String, String> map) throws Exception {
        //获取参数
        String type = map.get("type");
        String startDate = map.get("startDate");
        String endDate = map.get("endDate");

        //返回需要的数据
        Map<String, Object> result = new HashMap<String, Object>();
        List<String> dateList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        //起始时间和结束时间
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtils.parseString2Date(startDate));//开始时间日历
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(DateUtils.parseString2Date(endDate));//结束时间日历

        //如果时间在一个月内,则按天显示
        if (this.islessThanOneMonth(startDate, endDate)) {

            wrapListParaForLTMonth(type, dateList, numberList, cal, cal2);

        } else {//时间差大于一个月,按月展示
            wrapListPara4GTMonth(type,dateList, numberList, cal, cal2);

        }
        result.put("dateList", dateList);
        result.put("numberList", numberList);
        return result;

    }

    /**
     * 通过会员id查询风险评估数据,包括档案号,评估日期,评估状态
     * @param id
     * @return
     */
    public List<Map<String, Object>> findAccessDataById(Integer id) throws Exception {
        List<Map<String, Object>> list = memberMapper.findAccessDataById(id);
        //处理日期格式问题
        for (Map<String, Object> map : list) {
            Date assessTime = (Date) map.get("assessTime");
            String assessTimeStr = DateUtils.parseDate2String(assessTime);
            map.put("assessTime",assessTimeStr);
        }
        return list;
    }

    //查询体检报告名称
    public String findMedicalReport(String fileNumber) {
        String medicalReportName = memberMapper.findMedicalReportName(fileNumber);
        return medicalReportName;
    }

    @Override
    public AssessmentRisk findAccessReport(String fileNumber) {
        AssessmentRisk assessmentRisk = memberMapper.findAccessReport(fileNumber);
        return assessmentRisk;
    } /**
     * 当时间差大于一个月时,根据查询类型封装结果集合
     * @param type 类型
     * @param dateList x轴数据
     * @param numberList y轴数据
     * @param cal 开始时间日历对象
     * @param cal2 结束时间日历对象
     * @throws Exception
     */
    private void wrapListPara4GTMonth(String type,List<String> dateList, List<Integer> numberList, Calendar cal, Calendar cal2) throws Exception {
        while (true) {
            if (cal2.getTimeInMillis() - cal.getTimeInMillis() < 0) {
                break;
            }
            //获取当月1号
            Date firstDay4ThisMonth = DateUtils.getFirstDay4ThisMonth(cal.getTime());
            String firstDate4ThisMonthStr = DateUtils.parseDate2String(firstDay4ThisMonth);
            //获取当月最后一天
            Date lastDayOfMonth = DateUtils.getLastDayOfMonth(cal.getTime());
            String lastDayOfMonthStr = DateUtils.parseDate2String(lastDayOfMonth);
            //当月会员数
            Integer number =null;
            if ("新增会员".equals(type)) {
                number = memberMapper.findCountOfDateScope(firstDate4ThisMonthStr, lastDayOfMonthStr);
            }
            if ("预约人数".equals(type)) {
                number = orderMapper.findCountByDateScope(firstDate4ThisMonthStr, lastDayOfMonthStr);
            }
            if ("会员总数".equals(type)) {
                number = memberMapper.findMemberCountBeforeDate(lastDayOfMonthStr);
            }
            //拼接日期字符串如2020-05格式
            int index = firstDate4ThisMonthStr.lastIndexOf("-");
            String prefix = firstDate4ThisMonthStr.substring(0, index);

            //封装返回值
            dateList.add(prefix);
            numberList.add(number);

            cal.add(Calendar.MONTH, 1);//开始日期加1月
        }
    }

    /**
     * 根据查询类型,封装一个月内情况的结果集合
     *
     * @param type       查询类型
     * @param dateList   x轴数据
     * @param numberList y轴数据
     * @param startCal   开始时间日历对象
     * @param endCal     结束时间日历对象
     * @throws Exception
     */
    private void wrapListParaForLTMonth(String type, List<String> dateList, List<Integer> numberList, Calendar startCal, Calendar endCal) throws Exception {
        while (true) {//当结束时间大于当前时间,则一直循环
            if (endCal.getTimeInMillis() - startCal.getTimeInMillis() < 0) {
                break;
            }
            String currentDate = DateUtils.parseDate2String(startCal.getTime());
            Integer currentNumber = null;
            if ("新增会员".equals(type)) {
                //获取当前日期的会员数
                currentNumber = memberMapper.findCountByDate(currentDate);
            }
            if ("预约人数".equals(type)) {
                currentNumber = orderMapper.findCountByDate(currentDate);
            }
            if ("会员总数".equals(type)) {
                currentNumber = memberMapper.findMemberCountBeforeDate(currentDate);
            }

            //封装返回结果
            dateList.add(currentDate);
            numberList.add(currentNumber);

            startCal.add(Calendar.DATE, 1);//开始日期加1天
        }
    }


    private Boolean islessThanOneMonth(String startDate, String endDate) throws Exception {
        Date start = DateUtils.parseString2Date(startDate);
        Date end = DateUtils.parseString2Date(endDate);
        //时间戳相减
        long differenceValue = end.getTime() - start.getTime();
        //时间差是否小于32天
        return differenceValue < 3600 * 1000 * 24 * 32L;

    }
    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        //1.使用分页助手进行分页
        PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());

        //2.调用MemberMapper的findByCondition方法
        String queryString = pageBean.getQueryString();
        Page<Member> page = memberMapper.findByCondition(queryString);

        //3.封装放回对象
        return new PageResult(page.getTotal(), page.getResult());

    }

    @Override
    public void update(Member member) {
        memberMapper.edit(member);
    }
    public static void main(String[] args) throws Exception {
        Date lastDayOfMonth = DateUtils.getLastDayOfMonth();
        System.out.println(lastDayOfMonth);

    }


}
